package wnhz.com.business.groupshop.ui;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Paint;
import android.os.Build;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.google.gson.Gson;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.Callback;
import com.lzy.okgo.model.Response;
import com.umeng.socialize.UMShareListener;
import com.umeng.socialize.bean.SHARE_MEDIA;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindView;
import butterknife.ButterKnife;
import wnhz.com.business.MyApplication;
import wnhz.com.business.R;
import wnhz.com.business.base.BaseActivity;
import wnhz.com.business.base.BaseRVAdapter;
import wnhz.com.business.base.BaseViewHolder;
import wnhz.com.business.groupshop.adapter.QuanZiImageAdapter;
import wnhz.com.business.groupshop.bean.GoodsDetailInfoBean;
import wnhz.com.business.groupshop.bean.ShareInfo;
import wnhz.com.business.impl.ActionBarClickListener;
import wnhz.com.business.netcallback.DialogCallback;
import wnhz.com.business.netcallback.StringDialogCallback;
import wnhz.com.business.uitls.ToastUtils;
import wnhz.com.business.uitls.Url;
import wnhz.com.business.uitls.dialog.ShareDialog;
import wnhz.com.business.view.CircleImageView;
import wnhz.com.business.view.ExpandTextView;
import wnhz.com.business.view.MyScrollView;
import wnhz.com.business.view.NoScrollGridView;
import wnhz.com.business.view.TranslucentActionBar;

public class GoodsDetailsActivity extends BaseActivity implements View.OnClickListener, ActionBarClickListener {
    private static final String TAG = "RebateGoodsDetailsActivity";

    @BindView(R.id.tv_collect)//商品名字
    TextView tv_collect;
    @BindView(R.id.tv_sales)//商品简介
    TextView tv_sales;
    @BindView(R.id.tv_newPrice)//商品新价格
    TextView tv_newPrice;
    @BindView(R.id.ll_allComment)
    LinearLayout ll_allComment;
    @BindView(R.id.tv_comment)
    TextView tv_comment;
    @BindView(R.id.iv_userImg)//评论人头像
    CircleImageView iv_userImg;
    @BindView(R.id.tv_userName)//评论姓名
    TextView tv_userName;
    @BindView(R.id.tv_userComment)//评价内容
    ExpandTextView tv_userComment;
    @BindView(R.id.tv_commentTime)//评论发布时间
    TextView tv_commentTime;
    @BindView(R.id.webView)
    WebView webView;
    @BindView(R.id.ll_collect)
    LinearLayout ll_collect;
    @BindView(R.id.iv_collect)
    ImageView iv_collect;
    @BindView(R.id.tv_collect_status)
    TextView tv_collect_status;
    @BindView(R.id.lay)
    LinearLayout lay;
    @BindView(R.id.ll_have_comment)
    LinearLayout ll_have_comment;
    @BindView(R.id.ll_no_comment)
    LinearLayout ll_no_comment;

    @BindView(R.id.recycler_view)
    RecyclerView recycler_view;
    @BindView(R.id.rv_mass)
    RecyclerView rv_mass;
    @BindView(R.id.gridview)
    NoScrollGridView gridview;
    @BindView(R.id.actionbar)
    TranslucentActionBar actionbar;

    @BindView(R.id.ll_buy)
    LinearLayout ll_buy;
    @BindView(R.id.ll_pin)
    LinearLayout ll_pin;

    @BindView(R.id.tv_oldPrice)//商品原价
    TextView tv_oldPrice;
    @BindView(R.id.tv_look)
    TextView tvLook;
    @BindView(R.id.tv_comment_num)//评价数量
    TextView tvCommentNum;
    @BindView(R.id.iv_img)//评论商品图
    ImageView ivImg;
    @BindView(R.id.tv_sku)
    TextView tvSku;
    @BindView(R.id.sl_root)
    MyScrollView slRoot;
    @BindView(R.id.ll_kefu)
    LinearLayout llKefu;

    @BindView(R.id.iv_storeImg)//店铺图片
    CircleImageView iv_storeImg;
    @BindView(R.id.tv_storeName)//店铺名称
    TextView tv_storeName;
    @BindView(R.id.tv_storeDetail)//店铺简介
    TextView tv_storeDetail;
    @BindView(R.id.img_goodsdetail_main)//商品图片_主图
    ImageView img_goodsdetail_main;
    @BindView(R.id.tv_gropprice)
    TextView tv_gropprice;//团购价格
    @BindView(R.id.tv_nowbuyprice)
    TextView tv_nowbuyprice;

    private ArrayList<String> imageUrls = new ArrayList<>();
    private boolean isexpand;
    private String token = "";
    private boolean isCllected = false;
    private Map<String, Object> map = new HashMap<>();
    private String goodsId = "";
    private String store_id = "";
    private String goodsname = "";
    private String logo_pic;
    private String FromType;
    private List<String> list = new ArrayList<>();
    private ShareDialog shareDialog;
    private GoodsDetailInfoBean goodsDetail;
    private List<GoodsDetailInfoBean.InfoBean.BannerBean> bannerlist = new ArrayList<>();//轮播图
    private BaseRVAdapter adapter;
    private GoodsDetailInfoBean.InfoBean.CommentBean comment = new GoodsDetailInfoBean.InfoBean.CommentBean();//评论

    public static Intent createIntent(Context context, String goodsId, String logo_pic, String FromType) {
        Intent intent = new Intent(context, GoodsDetailsActivity.class);
        intent.putExtra("goodsId", goodsId);
        intent.putExtra("logo_pic", logo_pic);
        intent.putExtra("FromType", FromType);
        return intent;
    }

    private void parseIntent() {
        Intent intent = getIntent();
        goodsId = intent.getStringExtra("goodsId");
        logo_pic = intent.getStringExtra("logo_pic");
        FromType = intent.getStringExtra("FromType");
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_goods_details);
        ButterKnife.bind(this);
        parseIntent();
        actionbar.setData("商品详情", R.drawable.ic_lefft_white, null, R.drawable.ic_xiangqing_share, "分享", 0, this);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            this.getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            actionbar.setStatusBarHeight(getStatusBarHeight());
        }

        if (FromType.equals("1")) {
            lay.setVisibility(View.VISIBLE);
        }
        initView();
        initData();
    }

    private void initView() {
        ll_collect.setOnClickListener(this);
        ll_buy.setOnClickListener(this);
        ll_pin.setOnClickListener(this);
        tvLook.setOnClickListener(this);
        ll_allComment.setOnClickListener(this);

        initGoodsPic();
        //中间画横线
        tv_oldPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG);
        /**
         *  别人在开团
         */
        rv_mass.setLayoutManager(new LinearLayoutManager(GoodsDetailsActivity.this, LinearLayoutManager.VERTICAL, false));
        rv_mass.setAdapter(new BaseRVAdapter(GoodsDetailsActivity.this, list) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_mass;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView img = holder.getView(R.id.iv_storeImg);
                Glide.with(GoodsDetailsActivity.this).load(list.get(position)).into(img);
            }
        });

        /**
         * 商品详情页
         */
        WebSettings webSettings = webView.getSettings();
        //设置WebView属性，能够执行Javascript脚本
        webSettings.setJavaScriptEnabled(true);
        //设置可以访问文件
        webSettings.setAllowFileAccess(true);
        //关闭webview的放大缩小按钮
        webSettings.setDisplayZoomControls(false);
        //设置支持缩放
        webSettings.setBuiltInZoomControls(true);
        webSettings.setLoadWithOverviewMode(false);
        webSettings.setCacheMode(WebSettings.LOAD_DEFAULT);
        webSettings.setLayoutAlgorithm(WebSettings.LayoutAlgorithm.NORMAL);// 排版适应屏幕
        // 加载链接
        webView.loadUrl("http://www.baidu.com");
        //设置Web视图
        webView.setWebViewClient(new WebClient());
    }

    public class WebClient extends WebViewClient {

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);

        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);

        }
    }

    @Override
    public void onLeftClick() {
        finish();
    }

    @Override
    public void onRightClick() {
        //分享
        ShareInfo shareInfo = new ShareInfo();
        shareInfo.title = "小鸟云创";
        shareInfo.text = "专注各种商品商城，优惠多多！";
        shareInfo.targetUrl = "http://www.baidu.com";

        shareDialog = new ShareDialog(GoodsDetailsActivity.this, shareInfo, null, new UMShareListener() {
            @Override
            public void onResult(SHARE_MEDIA platform) {
                Toast.makeText(GoodsDetailsActivity.this, "分享成功", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onError(SHARE_MEDIA platform, Throwable t) {
                Toast.makeText(GoodsDetailsActivity.this, "分享失败", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onCancel(SHARE_MEDIA platform) {
                Toast.makeText(GoodsDetailsActivity.this, "分享取消", Toast.LENGTH_SHORT).show();
            }
        });
        shareDialog.show();
    }

    @Override
    public void onEditTextClick() {

    }

    private void initData() {
        Map<String, String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token", MyApplication.getInstance().getInfoBean().getToken());
        map.put("goodsId", goodsId);
        map.put("goods_type","1");//1.拼团  2.返利  3.免费
        bannerlist.clear();
        list.clear();
        OkGo.<String>post(Url.GOODS_DETAILS)
                .tag(this)
                .params(map,false)
                .execute(new StringDialogCallback(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("商品详情",response.body().toString());
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String re = jsonObject.optString("re");
                        if (re.equals("1")){
                            Gson gson = new Gson();
                            GoodsDetailInfoBean goodsDetailInfoBean = gson.fromJson(response.body(),GoodsDetailInfoBean.class);
                            goodsId = goodsDetailInfoBean.getInfo().getGoods_id();
                            logo_pic = goodsDetailInfoBean.getInfo().getLogo_pic();
                            store_id = goodsDetailInfoBean.getInfo().getStore_id();

                            bannerlist = goodsDetailInfoBean.getInfo().getBanner();
                            comment = goodsDetailInfoBean.getInfo().getComment();
                            for (int i = 0; i < bannerlist.size(); i++) {
                                list.add(bannerlist.get(i).getPic());
                            }
                            initGoodsPic();

                            //评论
                            tvCommentNum.setText("("+goodsDetailInfoBean.getInfo().getCommentCount()+")");
                            Glide.with(GoodsDetailsActivity.this).load(comment.getHeadimg()).into(iv_userImg);
                            tv_userName.setText(comment.getNickname());
                            tv_commentTime.setText(comment.getPosttime());
                            Glide.with(GoodsDetailsActivity.this).load(goodsDetailInfoBean.getInfo().getLogo_pic()).into(ivImg);
                            /**
                             * 评论的部分
                             */
                            tv_userComment.setExpand(isexpand);
                            tv_userComment.setExpandStatusListener(new ExpandTextView.ExpandStatusListener() {
                                @Override
                                public void statusChange(boolean isExpand) {
                                    isexpand = isExpand;
                                }
                            });
                            tv_userComment.setText(comment.getContent());

                            //商品
                            goodsname = goodsDetailInfoBean.getInfo().getGoods_name();
                            tv_collect.setText(goodsDetailInfoBean.getInfo().getGoods_name());
                            tv_sales.setText(goodsDetailInfoBean.getInfo().getGoods_title());
                            tv_newPrice.setText("¥"+goodsDetailInfoBean.getInfo().getPrice());
                            tv_oldPrice.setText("¥"+goodsDetailInfoBean.getInfo().getOprice());

                            //店铺
                            Glide.with(GoodsDetailsActivity.this).load(goodsDetailInfoBean.getInfo().getStore_logo()).into(iv_storeImg);
                            tv_storeName.setText(goodsDetailInfoBean.getInfo().getStore_name());
                            tv_storeDetail.setText("全部商品 "+goodsDetailInfoBean.getInfo().getStore_count()+"件  已拼团"+goodsDetailInfoBean.getInfo().getGroup_count()+"次");

                            tv_gropprice.setText("¥"+goodsDetailInfoBean.getInfo().getGroup_price());
                            tv_nowbuyprice.setText("¥"+goodsDetailInfoBean.getInfo().getPrice());
                        }
                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                    }
                });

    }


    private void initGoodsPic() {
        /**
         *  商品图
         */
        recycler_view.setLayoutManager(new LinearLayoutManager(GoodsDetailsActivity.this, LinearLayoutManager.HORIZONTAL, false));
        adapter = new BaseRVAdapter(GoodsDetailsActivity.this, bannerlist) {
            @Override
            public int getLayoutId(int viewType) {
                return R.layout.item_one_item_layout;
            }

            @Override
            public void onBind(BaseViewHolder holder, int position) {
                ImageView img = holder.getView(R.id.iv_img);
                Glide.with(GoodsDetailsActivity.this).load(bannerlist.get(position).getPic()).into(img);
            }
        };
        adapter.addItemClickListener(new BaseRVAdapter.OnItemClickListener() {
            @Override
            public void itemSelect(int position) {
                Glide.with(GoodsDetailsActivity.this).load(bannerlist.get(position).getPic()).into(img_goodsdetail_main);
            }
        });
        recycler_view.setAdapter(adapter);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.ll_allComment:
                startActivity(AllCommentActivity.createIntent(GoodsDetailsActivity.this, goodsId,""));
                break;
            case R.id.ll_collect:
                if (isCllected) {
                    isCllected = false;
                    iv_collect.setBackgroundResource(R.drawable.ic_home_uncheck);
                    tv_collect_status.setText("收藏");
                    toCollect("2");
                } else {
                    isCllected = true;
                    iv_collect.setBackgroundResource(R.drawable.ic_home_checked);
                    tv_collect_status.setText("已收藏");
                    toCollect("1");
                }
                break;
            case R.id.ll_buy://单独购买
                startActivity(AddCartActivity.createIntent(GoodsDetailsActivity.this, goodsId,store_id,logo_pic,goodsname));
                break;
            case R.id.ll_pin://立即拼团
                startActivity(AddCartActivity.createIntent(GoodsDetailsActivity.this, goodsId,store_id,logo_pic,goodsname));
                break;
            //进店看看
            case R.id.tv_look:
                startActivity(StoreActivity.createIntent(this));
                break;

        }
    }

    /**
     * 收藏/取消收藏
     */
    private void toCollect(String type) {
        Map<String,String> map = new HashMap<>();
        if (MyApplication.getInstance().getInfoBean() == null){
            MyApplication.getInstance().BackLoginActivity();
            return;
        }
        map.put("token",MyApplication.getInstance().getInfoBean().getToken());
        map.put("goods_type","1");//1.拼团  2.返利  3.免费
        map.put("type",type);//1-收藏  2-取消收藏
        map.put("storeId",store_id);
        map.put("goodsId",goodsId);
        OkGo.<String>post(Url.GOODS_COLLECT)
                .tag(this)
                .params(map,false)
                .execute(new DialogCallback<String>(this) {
                    @Override
                    public void onSuccess(Response<String> response) {
                        Log.e("商品收藏",response.body());
                        JSONObject jsonObject = null;
                        try {
                            jsonObject = new JSONObject(response.body().toString());
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                        String re = jsonObject.optString("re");
                        String num = jsonObject.optString("num");
                        if (re.equals("1")) {
                            if (num.equals("0")){
                                MyToast("收藏成功");
                            }else {
                                MyToast("取消收藏成功");
                            }
                        } else {
                            MyToast("收藏失败,请稍后再试");
                        }

                    }

                    @Override
                    public void onFinish() {
                        super.onFinish();
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        MyToast("收藏失败,请稍后再试");
                    }
                });
    }


}
